package com.bookmall.cart.interceptor;

import com.bookmall.common.constant.CartConstant;
import com.bookmall.common.constant.DefaultDataConstants;
import com.bookmall.common.constant.ExceptionTypeConstants;
import com.bookmall.common.entity.to.MemberInfoTo;
import com.bookmall.common.entity.to.UserInfoTo;
import com.bookmall.common.exception.LogOutException;
import com.bookmall.common.exception.LoginException;
import com.ruoyi.common.core.text.UUID;
import com.ruoyi.common.core.utils.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * 购物车拦截器，用于判断用户的登录状态。并封装传递给controller目标请求
 * @Author 胡菜鸡
 * @Create 2022-04-15-14:21
 */
@Component
public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<MemberInfoTo> threadLocal = new ThreadLocal<>();

    /**
     * 目标方法执行之前的拦截器
     * @author 胡菜鸡
     * @date 2022/4/15 14:23
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        MemberInfoTo member = (MemberInfoTo) session.getAttribute(DefaultDataConstants.LOGIN_USER);
        if(member == null){
            request.getSession().setAttribute("msg", "请先登录");
            //用户还未登录
            throw new LogOutException("用户未登录", ExceptionTypeConstants.USER_LOGOUT);
        } else {
            //如果已经登录，则刷新session持续时间
            session.setAttribute(DefaultDataConstants.LOGIN_USER, member);
        }

        //用户已登录，放行
        threadLocal.set(member);
        return true;
    }
}
